package com.caiyi.financial.nirvana.sms.gateway.http;

import com.alibaba.fastjson.JSON;
import com.caiyi.financial.nirvana.sms.entity.SmsReceiveMessage;
import com.caiyi.financial.nirvana.sms.enums.SmsMsgStatusEnum;
import com.caiyi.financial.nirvana.sms.jedis.JedisKey;
import com.caiyi.financial.nirvana.sms.jedis.JedisService;
import com.caiyi.financial.nirvana.sms.queue.NotifyQueueEntity;
import com.caiyi.financial.nirvana.sms.queue.ReceiveMsgQueueEntity;
import com.caiyi.financial.nirvana.sms.queue.SendQueueEntity;
import com.caiyi.financial.nirvana.sms.util.MD5Util;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


/**
 * \* User: ywg
 * \* 助通通道 支持行业，营销
 * \
 */
public class ZhuTongGateway extends BaseGateway {
    private static final Logger logger = LoggerFactory.getLogger(ZhuTongGateway.class);
    private static final String SUCCESS_CODE = "1";

    @Override
    public void sendMessage(SendQueueEntity entity) {
        int status = SmsMsgStatusEnum.REQUEST_FAIL.index;
        String result = "";
        try {
            Map param = buildParam(entity);
            String response = doPost(info.getServerAddr(), param);
            if (response == null) {
                result = "网关请求超时";
                return;
            }
            String[] resultList = response.split(",");
            if (SUCCESS_CODE.equals(resultList[0])) {
                status = SmsMsgStatusEnum.REQUEST_SUCCESS.index;
            }
            result = resultList[1];
            logger.info("ZhuTongGateway send url : {}, params : {}, result : {}", info.getServerAddr(), param, response);
        } catch (Exception e) {
            logger.error("ZhuTongGateway sendMessage error ! ", e);
        } finally {
            this.handlerResponse(entity, result, status);
        }

    }


    private Map buildParam(SendQueueEntity entity) throws Exception {
        Map<String, String> map = new HashMap<>();
        map.put("username", info.getAccount());
        DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
        String tkey = format.format(LocalDateTime.now());
        map.put("tkey", tkey);
        String password = MD5Util.encode(MD5Util.encode(info.getPassword()).toLowerCase() + tkey).toLowerCase();
        map.put("password", password);
        map.put("mobile", entity.getPhone());
        map.put("content", entity.getContent());
        map.put("xh", entity.getAccessNumber());
        return map;
    }

    //推送
    @Override
    public boolean notifyStatus(NotifyQueueEntity entity) {
        try {
            String param = entity.getParam();
            logger.info("ZhuTongGateway notifyStatus param : {}", param);
            Map<String, String> paramMap = JSON.parseObject(param, Map.class);
            String report = paramMap.get("param");
            if (StringUtils.isBlank(report)) {
                return false;
            }
            String[] messageList = report.split(";");
            handlerStatus(messageList);
            logger.info("ZhuTongGateway notifyStatus result is {}", report);
            return true;
        } catch (Exception e) {
            logger.error("ZhuTongGateway notifyStatus error ! ", e);
        }
        return false;
    }

    @Override
    public boolean receiveMsg(ReceiveMsgQueueEntity entity) {
        return false;
    }

    //主动获取
    public boolean queryStatus() {
        try {
            String url = info.getServerAddr().replace("sendSmsBatch.do", "batchreport.do");
            String jsonStr = doPost(url);
            if (jsonStr == null || !jsonStr.contains(";")) {
                return false;
            }
            String[] messageList = jsonStr.split(";");
            handlerStatus(messageList);
            logger.info("ZhuTongGateway queryStatus result is {}", jsonStr);
        } catch (Exception e) {
            logger.error("ZhuTongGateway queryStatus error ! ", e);
            return false;
        }
        return false;
    }

    private void handlerStatus(String[] messageList) {
        for (int i = 0; i < messageList.length; i++) {
            int status = SmsMsgStatusEnum.SEND_FAIL.index;
            String[] phoneMessageList = messageList[i].split(",");
            String remoteId = phoneMessageList[0] + phoneMessageList[1];
            String messageId = JedisService.hget(JedisKey.SMS_REMOTE_ID_MESSAGE_ID, remoteId);
            JedisService.hdel(JedisKey.SMS_REMOTE_ID_MESSAGE_ID, remoteId);
            if (StringUtils.isBlank(messageId)) {
                logger.warn("ZhuTongGateway queryStatus messageId is null params : {}", remoteId);
            }
            if (SUCCESS_CODE.equals(phoneMessageList[2])) {
                status = SmsMsgStatusEnum.SEND_SUCCESS.index;
            }
            String result = phoneMessageList[2];
            receiveReport(status, messageId, result);
        }
    }

    //主动获取上行信息
    public boolean queryReceiveMsg() {
        try {
            String url = info.getServerAddr().replace("sendSmsBatch.do", "batchreply.do");
            String jsonStr = doPost(url);
            logger.info("ZhuTongGateway queryReceiveMsg  result : {}", jsonStr);
            if (jsonStr == null || !jsonStr.contains("[;]")) {
                return false;
            }
            String[] messageList = jsonStr.split("\\[;]");
            for (int i = 0; i < messageList.length; i++) {
                String[] oneList = messageList[i].split("\\[,]");
                SmsReceiveMessage smsReceiveMessage = new SmsReceiveMessage();
                smsReceiveMessage.setMessageId(oneList[2]);
                smsReceiveMessage.setCreateTime(new Date());
                smsReceiveMessage.setContent(oneList[1]);
                String accessNumber = oneList[3];
                String extend = accessNumber.length() > 3 ? accessNumber.substring(accessNumber.length() - 3) : accessNumber;
                String account = JedisService.get(String.format(JedisKey.SMS_EXTEND_ACCOUNT, extend));
                smsReceiveMessage.setAccessNumber(accessNumber);
                smsReceiveMessage.setAccount(account);
                smsReceiveMessage.setPhone(oneList[0]);
                receiveMessage(smsReceiveMessage);
            }
            return true;
        } catch (Exception e) {
            logger.error("ZhuTongGateway queryReceiveMsg error ! ", e);
        }
        return false;
    }

    @Override
    public int queryBalance() {
        try {
            String url = info.getServerAddr().replace("sendSmsBatch.do", "balance.do");
            String jsonStr = doPost(url);
            return Integer.parseInt(jsonStr);
        } catch (Exception e) {
            logger.error("ZhuTongGateway queryBalance error ! ", e);
        }
        return 0;
    }

    public String doPost(String url) {
        Map<String, Object> map = new HashMap<>();
        map.put("username", info.getAccount());
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
        String tkey = format.format(new Date());
        map.put("tkey", tkey);
        String password = MD5Util.encode(MD5Util.encode(info.getPassword()).toLowerCase() + tkey).toLowerCase();
        map.put("password", password);
        return doPost(url, map);
    }
}
